package com.david.reader.txt

import android.content.Context
import android.os.Environment
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import java.io.File


@Database(entities = [TxtPage::class], version = 1)
abstract class TxtDataBase: RoomDatabase(){

    private var databaseInstance: TxtDataBase? = null

    @Synchronized
    open fun getInstance(context: Context): TxtDataBase? {
        if (databaseInstance == null) {
            databaseInstance = Room
                .databaseBuilder(
                    context.applicationContext,
                    TxtDataBase::class.java,
                    DATABASE_NAME
                )
                .build()
        }
        return databaseInstance
    }


    companion object{
        public val DATABASE_NAME = "my_db"//一个txt文件生成一个数据库

        open fun getTxtDataBase(context: Context, dataBaseName: String): TxtDataBase?{//阅读页调用，在页面destroy时销毁即可
            var dbPath = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS)?.absolutePath+
                    File.separator+"db"+File.separator+ dataBaseName +".db";

            return Room
                .databaseBuilder(
                    context.applicationContext,
                    TxtDataBase::class.java,
                    dbPath
                )
                .build();
        }
    }



    abstract fun txtPageDao(): TxtPageDao?
}